<?php
namespace Leaps\Cache\Adapter;
use Memcached;
use Leaps\Cache\Section;
use Leaps\Cache\AdapterInterface;

class Memcached implements AdapterInterface {

	/**
	 * Memcached实例。
	 *
	 * @var Memcached
	 */
	protected $memcached;

	/**
	 * Create a new Memcached store.
	 *
	 * @param  Memcached  $memcached
	 * @param  string     $prefix
	 * @return void
	 */
	public function __construct(Memcached $memcached)
	{
		$this->memcached = $memcached;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::get()
	 */
	public function get($key)
	{
		$value = $this->memcached->get($key);
		if ($this->memcached->getResultCode() == 0)
		{
			return $value;
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::set()
	 */
	public function set($key, $value, $minutes)
	{
		$this->memcached->set($key, $value, $minutes * 60);
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::forever()
	 */
	public function forever($key, $value)
	{
		return $this->put($key, $value, 0);
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::delete()
	 */
	public function delete($key)
	{
		$this->memcached->delete($key);
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::flush()
	 */
	public function flush()
	{
		$this->memcached->flush();
	}

	/**
	 * Begin executing a new section operation.
	 *
	 * @param  string  $name
	 * @return \Leaps\Cache\Section
	 */
	public function section($name)
	{
		return new Section($this, $name);
	}

	/**
	 * Get the underlying Memcached connection.
	 *
	 * @return \Memcached
	 */
	public function getMemcached()
	{
		return $this->memcached;
	}
}